//
//  YAHomeController.swift
//  于昂微博
//
//  Created by 鱼龙之梦 on 15/8/31.
//  Copyright © 2015年 鱼龙之梦. All rights reserved.
//

import UIKit
import SVProgressHUD
let YAStatusNormalCellID = "YAStatusNormalCellID"
let YAStatusForwardCellID = "YAStatusForwardCellID"
class YAHomeController: YABaseTableViewController {
    private lazy var statusListVM = YAStatusListVM()
    private lazy var picBrowserAnimator = YAPicBrowserAnimator()
    func loadData(){
        refreshControl?.beginRefreshing()
        statusListVM.loadStatues(isPull: pullupView.isAnimating()).subscribeNext({ (result) -> Void in
            let count = (result as! NSNumber).integerValue
           // printLog("更新\(count)条微博")
            self.showPullTipView(count)
            }, error: { (error) -> Void in
                printLog(error)
                self.endLoadData()
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
            }) {
                self.endLoadData()
                self.tableView.reloadData()
        }
        
    }
    private func endLoadData(){
        self.refreshControl?.endRefreshing()
        self.pullupView.stopAnimating()
    }
    private lazy var pulldownTipLabel:UILabel = {
        let label = UILabel(title: nil, color: UIColor.whiteColor(), fontSize: 18)
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = NSTextAlignment.Center
        self.navigationController?.navigationBar.insertSubview(label, atIndex:0)
        return label
        }()
    private func showPullTipView(count:Int){
        let title = count == 0 ? "没有新微博" : "刷新到\(count)条微博"
        let height:CGFloat = 44
        let rect = CGRect(x: 0, y: -2 * height, width: UIScreenWidth, height: height)
        pulldownTipLabel.text = title
        pulldownTipLabel.frame = rect
        UIView.animateWithDuration(1.2, animations: { () -> Void in
            self.pulldownTipLabel.frame = CGRectOffset(rect, 0, 3*height)
            }) { (_) -> Void in
                UIView.animateWithDuration(2.0){
                    self.pulldownTipLabel.frame = rect
                }
        }
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        if !YAUserAcountVM.sharedUserAccount.userLogon{
            visitView?.setupInfo(nil, message: "关注一些人，回这里看看有什么惊喜")
            return
        }
        tableView.scrollsToTop = true
        //监听图片cell选中时发来的通知
        NSNotificationCenter.defaultCenter().addObserverForName(YAStatusPictureViewSelectedNotification, object: nil, queue: nil) {[weak self](notification) -> Void in
            guard let urls = notification.userInfo![YAStatusPictureViewSelectedPhotoURLsKey] as? [NSURL] else {
                return
            }
            guard let indexPath = notification.userInfo![YAStatusPictureViewSelectedIndexPathKey] as? NSIndexPath else{
                return
            }
            //获取图片视图的对象
            guard let picView = notification.object as? YAStatusPictureView else {
                return
            }
            let vc = YAPicBrowserController(urls: urls, indexPath: indexPath)
            // 使用转场动画代理
            vc.transitioningDelegate = self?.picBrowserAnimator
            //将展示模式改为自定义
            vc.modalPresentationStyle = UIModalPresentationStyle.Custom
            //计算位置
            let fromRect = picView.screenRect(indexPath)
            let toRect = picView.fullScreenRect(indexPath)
            self?.picBrowserAnimator.prepareAnimator(picView,fromRect:fromRect, toRect: toRect, url: urls[indexPath.item])
            self?.presentViewController(vc, animated: true, completion: nil)
        }
        prepareTableView()
        loadData()
        
    }
     //MARK:--- 销毁通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //MARK:TableView的一些初始化
    private func prepareTableView(){
        self.tableView.registerClass(YANormalStatusCell.self, forCellReuseIdentifier: YAStatusNormalCellID)
        tableView.registerClass(YAStatusForwardCell.self, forCellReuseIdentifier: YAStatusForwardCellID)
        //一下两句是自动处理行高：条件是在YAStatusCell的ContentView中的最后一个子控件在其底部有个约束
        tableView.estimatedRowHeight = 300
        //tableView.rowHeight = 300//UITableViewAutomaticDimension
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        refreshControl = YARefreshControl()
        //问题：这里事件监听的是刷新控件的什么值
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        //systemRefreshControl()
        tableView.tableFooterView = pullupView
    }
    private lazy var pullupView:UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        indicator.color = UIColor.darkGrayColor()
        return indicator
        }()
    //MARK:--- “更新控件”的应用
    private func systemRefreshControl(){
        refreshControl = UIRefreshControl()
        refreshControl?.backgroundColor = UIColor.redColor()
        printLog(refreshControl?.frame)
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        refreshControl?.tintColor = UIColor.clearColor()
        let v = UILabel(frame: refreshControl!.bounds)
        v.text = "更新中..."
        v.textColor = UIColor.whiteColor()
        v.textAlignment = NSTextAlignment.Center
        v.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
        refreshControl?.addSubview(v)
    }
}

//MARK:将Cell的数据源方法分离出来
extension YAHomeController{
    // 1. 数据行数
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListVM.statues.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let statusVM = statusListVM.statues[indexPath.row] as! YAStatusVM
        
        let cell = tableView.dequeueReusableCellWithIdentifier(statusVM.cellId, forIndexPath: indexPath) as! YAStatusCell
        
        cell.statusVM = statusVM
        
        //判断视图上推加载历史数据
        if(indexPath.row == statusListVM.statues.count - 1) && !pullupView.isAnimating() {
            pullupView.startAnimating()
            loadData()
        }
        cell.cellDelegate = self

        return cell
    }
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let viewModel = statusListVM.statues[indexPath.row] as! YAStatusVM
        if viewModel.rowHeight>0{
            return viewModel.rowHeight
        }
        let cell = tableView.dequeueReusableCellWithIdentifier(viewModel.cellId) as! YAStatusCell
        
        viewModel.rowHeight = cell.rowHeight(viewModel)
        return viewModel.rowHeight
    }
}
extension YAHomeController:YAStatusCellDelegate{
    func statusCellDidClickURL(url: NSURL) {
        let vc = YAWebViewController()
        vc.url = url
        vc.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(vc, animated: true)
        
    }
}